(function(window, undefined, App){

App.config = {
	appName: '七彩坊',
	appId: 100380341,
	host: 'http://app100670476.qzone.qzoneapp.com/mobile/'
}

App.view = {};
App.model = {};
App.collection = {}

App.el = $('body');


// 初始化
App.init = function(){
	document.addEventListener("deviceready", onDeviceReady, false);
	document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);

	// 初始化用户
	App.model.user = new User();

	// 开启路由
	App.router = new Router();
	Backbone.history.start();
}

// PhoneGap加载完毕
var onDeviceReady = function() {

	App.checkConnection();

	document.addEventListener("backbutton", App.backBtn, false);
	//document.addEventListener("menubutton", eventMenuButton, false);
	//document.addEventListener("searchbutton", eventSearchButton, false);
}

// User
var User = Backbone.Model.extend({

	localStorage: new Store("user"),

	initialize: function() {
		this.on('change', this.sync, this);

		this.on('all', this.all, this)
		
		var data = _.find(
			this.localStorage.findAll(), 
			function(value, index, list){
				return value.auth ? true : false;
			}, this);

		!_.isEmpty(data) && this.set(data);
	},

	all: function(){
		console.log(arguments);
	},

	sync: function(method, model, options){
		console.log('user sync');
		if(method == 'delete'){
			this.localStorage.destroy(this);
			options.success();
		} else {
			this.id = this.get('openid');
			console.log(this.id);
			this.id && this.localStorage.update(this);
		}

	}
});

// 登录选择界面
var AccountView = Backbone.View.extend({

	id: 'account',

	template: tpl['account'],

	className: 'box pt-page-moveFromRight',

	events: {
		'tap .js_return': 'goback',
		'tap .qq_login': 'qqLogin'
	},

	initialize: function () {
		$('#' + this.id).remove();
		_.bindAll(this, 'goback', 'qqLogin');

		App.el.append(this.el);
		this.render();
	},


	render: function () {
		console.log('account render');

		$(this.el).html(this.template({}))

		var func = _.bind(function(){
			$(this.el).addClass('visible');
		}, this)

		_.delay(func, 100);

		return this;
	},

	goback: function(){
		$(this.el).removeClass('pt-page-moveFromRight').addClass('pt-page-moveToRight');
	},

	qqLogin: function(){
		App.Login.qq();
	}
});

// Login
App.Login = (function(L){

	var getHash = function(url) {
		var match = url.match(/#(.*)$/);
		return match ? match[1] : '';
	}

	var queryString = function(hash, item) {
		var svalue = hash.match(new RegExp("[\?\&]" + item + "=([^\&]*)(\&?)", "i"));
		return svalue ? svalue[1] : svalue;
	}

	L.init = function(func, callback, context){

		if(!L.check()){
			App.view.account = new AccountView();
			App.model.user.on('change', callback, context);
		} else {
			func && func();
		}
	}

	L.check = function() {
		return (App.model.user.get("auth")? true : false);
	};

	L.qq = function() {
		console.log('qqLogin start');

		if(!$.os.android){
			App.model.user.set({
				openid: 'C2AB78672D2DC3982C97DA92AD593874',
				auth: 'ed6880d4e48752a6e4a39fca08339c1e725e6b4c3cb2b4b1359a7f7c6c1fdf2d591a6c484e7210b4096a5a379df8f2e0',
				access_token: '7A203272E69A3EECE04C1582E51873BA'
			})
			App.view.account.goback();
			return;
		}
		
		var uri = 'http://app100670476.qzone.qzoneapp.com/mobile/logon/qq.ngi',
			loginUrl = 'https://graph.qq.com/oauth2.0/authorize?response_type=code&scope=get_user_info,get_info,add_share&client_id=' + App.config.appId + '&display=mobile&redirect_uri=' + uri, 
			ref = window.open(loginUrl, '_blank', 'location=no');


		ref.addEventListener('loadstart', function(e) { L.success(ref, e.url) });
		ref.addEventListener('loadstop', function(e){ L.success(ref, e.url) });
	};

	L.success = function(ref, url) {
		console.log('login qq: ', url);

		var hash = getHash(url),
			auth = queryString(hash, 'auth'),
			openid = queryString(hash, 'openid'),
			access_token = queryString(hash, 'access_token');
		

		if(auth){
			App.model.user.set({
				openid: openid,
				auth: auth,
				access_token: access_token
			})

			ref.close();
			App.view.account.goback();
		}
	}

	L.logout = function() {
		console.log('log out success');

		App.model.user.destroy();
		App.model.user.unset();
		App.model.user.clear();
	};

	return L;

})(App.Login || {});


var timeStamp,
	ztback = false;

App.backBtn = function(e) {
	console.log(e);

	if(ztback){
		e.preventDefault();
		return false;
	}

	if(timeStamp){
		var sub = parseInt(e.timeStamp) - parseInt(timeStamp);

		if(sub > 3000){
			timeStamp = e.timeStamp;
			plugins.Toast.shortshow('再按一次退出应用');
		} else {
			navigator.app.exitApp();
		}

	} else {
		timeStamp = e.timeStamp;
		plugins.Toast.shortshow('再按一次退出应用');
	}
}

App.checkConnection = function() { 
	var networkState = navigator.network.connection.type;        

	var states = {}; 
	states[Connection.UNKNOWN]  = 'Unknown connection'; 
	states[Connection.ETHERNET] = 'Ethernet connection'; 
	states[Connection.WIFI]     = 'WiFi connection'; 
	states[Connection.CELL_2G]  = 'Cell 2G connection'; 
	states[Connection.CELL_3G]  = 'Cell 3G connection'; 
	states[Connection.CELL_4G]  = 'Cell 4G connection'; 
	states[Connection.NONE]     = 'No network connection'; 

	plugins.Toast.shortshow(states[networkState]);

	if(states[networkState] == 'No network connection' || typeof states[networkState] == "undefined"){
		plugins.Toast.longshow('警告，应用需要连接网络获得数据，请打开网络');
		_.delay(function(){
			navigator.app.exitApp();
		}, 3000)
	}
};

// share
App.share = (function(){
	return {
		qzone: function(opts, callback){
			var params = {
				format: 'json',
				fromurl: 'http://rc.qzone.qq.com/100670476',
				site: 'http://rc.qzone.qq.com/100670476',
				oauth_consumer_key: App.config.appId
			}

			_.extend(params, opts, {
				openid: App.model.user.get('openid'),
				access_token: App.model.user.get('access_token'),
				oauth_consumer_key: App.config.appId,
			});

			Backbone.sync({
				url: 'https://graph.qq.com/share/add_share',
				data: params,
				success: callback
			})
		}
	}
})();

// Camera
App.Camera = (function(C) {
	C.config = C.config || {};

	if ( typeof Camera !== 'undefined' ) {
		C.config.destinationType = Camera.DestinationType.FILE_URI;     // cameraOptions: destinationType
		C.config.sourceType = Camera.PictureSourceType.PHOTOLIBRARY;    // cameraOptions: sourceType
		C.config.mediaType = Camera.MediaType.PICTURE;                  // cameraOptions: mediaType
	}

	// Photo quality and editing options:
	C.config.quality = 42;                                          // cameraOptions: quality
	C.config.targetWidth = 500;                                     // cameraOptions: targetWidth
	C.config.targetHeight = 500;                                    // cameraOptions: targetHeight
	C.config.allowEdit = false;                                      // cameraOptions: allowEdit
	C.config.correctOrientation = true;                             // cameraOptions: correctOrientation

	// Saving options:
	C.config.encodingType = (typeof Camera !== 'undefined') ? Camera.EncodingType.JPEG : 0;
	C.config.saveToPhotoAlbum = false;

	// iOS-specific (to specify popover location in iPad):
	C.config.popoverOptions = ((typeof Camera !== 'undefined') && (typeof CameraPopoverOptions !== "undefined")) ? new CameraPopoverOptions(220, 600, 320, 480, Camera.PopoverArrowDirection.ARROW_DOWN) : null;    // cameraOptions: popoverOption

	C.init = function(args, fn) {

		navigator.notification.confirm(  
			'请选择图片来源',
			function(i){
				console.log(i)
				C.onCapture(i, args, fn)
			},
			'选择图片',
			'取消, 从图库选择, 拍照'
		);
	};

	C.onCapture = function(i, args, success) {
		console.log('onCapture', i, args);

		var i = parseInt(i),
			saveToPhotoAlbum = args.saveToPhotoAlbum;

		switch (i) {
			case 3: // 拍照
				C.config.sourceType = Camera.PictureSourceType.CAMERA;
				saveToPhotoAlbum = true;
				break;
			case 2: // 从图库选择
				C.config.sourceType = Camera.PictureSourceType.PHOTOLIBRARY;
				saveToPhotoAlbum = false;
				break;
			/* case 2:
				C.config.sourceType = Camera.PictureSourceType.SAVEDPHOTOALBUM;
				break; */
			default:
				return;
		}

		navigator.camera.getPicture(function(img) { success(i, img); }, C.onCaptureError, {
			quality: args.quality || C.config.quality,
			destinationType: C.config.destinationType,
			sourceType: C.config.sourceType,
			allowEdit: args.allowEdit || C.config.allowEdit,
			encodingType: C.config.encodingType,
			targetWidth: args.targetWidth || C.config.targetWidth,
			targetHeight: args.targetHeight || C.config.targetHeight,
			mediaType: C.config.mediaType,
			saveToPhotoAlbum: saveToPhotoAlbum || C.config.saveToPhotoAlbum,
			correctOrientation: C.config.correctOrientation,
			popoverOptions: C.config.popoverOption
		});
	};

	C.onCaptureError = function(msg) {

		console.log('on capture error: ', msg);

	};

	return C;
})(App.Camera || {});


// upload
App.Upload = (function(U) {

    U.img = function(args, onSuccess, onFail) {
        doUpload({
            uploadUrl: args.uploadUrl,
            itemUrl: args.img,
            fileKey: args.fileKey || 'image',
            mimeType: 'image/jpeg',
            data: args.data || {}
        }, onSuccess, onFail);
    };

    U.audio = function(args, onSuccess, onFail) {
       	App.loading({msg: '正在上传...'})
        audioConvert(args.audio, function(res) {
            var data = args.data;

            if ( data.voice.indexOf('.wav') > 0 ) data.voice = res.url;
            doUpload({
                uploadUrl: args.uploadUrl || '/upload_voice.json',
                itemUrl: res.url,
                fileKey: args.fileKey || 'voice',
                mimeType: 'audio/mpeg' || args.mimeType,
                data: data || {}
            }, onSuccess, onFail);
        });
    };

    function doUpload(args, onSuccess, onFail) {

    	console.log(args);

        var options = new FileUploadOptions(),
            ft = new FileTransfer(),
            params,
            uploadUrl = args.uploadUrl;

       
       	var load = App.dialog({
			dialogId: 'loading',
			html:  '<div><img src="./img/loading.png" alt="loading">加载中...</div>',
		});

        options.fileKey = args.fileKey;

        // 取文件名
        options.fileName = args.itemUrl.substr( args.itemUrl.lastIndexOf('/') + 1 );
        options.fileName = options.fileName.substr(0, options.fileName.lastIndexOf('?'));

        options.mimeType = args.mimeType;

        params = $.extend({
            auth: App.model.user.get('auth'),
            of: 'json'
        }, args.data);

        options.params = params;

        console.log('start upload: options + item url + upload url', options, args.itemUrl, uploadUrl);

        ft.upload(args.itemUrl, encodeURI(uploadUrl), function(res) {
            console.log('do upload success: ', res);
            onSuccess && onSuccess($.parseJSON(res.response));
           	load.close()
        }, function(res) {
            console.log('do upload failed: ', res);
            navigator.notification.alert('', null, '上传出错了，请重试');
            onFail && onFail(res);
           	load.close()
        }, options);
    }

    return U;
})(App.Upload || {});

// 学堂
var School = Backbone.Model.extend({

	defaults: function(){},

	initialize: function() {
	},

	toggle: function(){
		this.set({isCollect: !this.get("isCollect")});
	}
});

var Schools = Backbone.Collection.extend({

	model: School,

	url: App.config.host + 'items/list.ngi',

	initialize: function() {},

	parse: function(resp) {
		return resp.data;
	}
});

var SchoolView = Backbone.View.extend({

	id: 'school',

	className: 'box',
	
	template: tpl.school,

	events: {
		'tap article': 'toItem'
	},

	initialize: function () {

		this.collection.bind('sync', this.render, this);
		_.bindAll(this, 'toItem');

		App.el.append($(this.el));
		this.show().render();
	},

	show: function(args){
		console.log('school show');
		
		$('.box').addClass('hide');
		$(this.el).removeClass('hide');

		this.collection.fetch();
		return this;
	},

	render: function (args) {
		console.log('school render');

		$(this.el).html( this.template({items: this.collection.toJSON()}) );

		if(this.collection.length > 0){
			_.delay(_.bind(function(){
				App.scroll && (App.scroll.destroy(), App.scroll = null );
				App.scroll = new iScroll('wrapper_school', {
					fadeScrollbar: true,
					hideScrollbar: true
				});
			}, this), 100);
		}
		return this;
	},

	toItem: function(e){
		var model = this.collection.at($(e.currentTarget).index());

		console.log(model.toJSON());
		App.view.schoolItem = new SchoolItemView({
			model: model
		})
	}
});

var SchoolItemView = Backbone.View.extend({

	id: 'schoolItem',

	className: 'box pt-page-moveFromRight hidden',

	events: {
		"tap #school_share": "toggleShare",
		"tap #school_love": "toggleLove",
		"tap #select_share_list li": "toShare",
		'tap .btn_z': 'toLeave'
	},

	template: tpl['schoolItem'],

	initialize: function () {
		$('#' + this.id).remove();
		_.bindAll(this, "toggleShare", "toggleLove", "toShare", 'toLeave');

		this.model.on('change', this.render, this);

		App.el.append(this.el);
		this.render();
	},

	render: function () {
		console.log('school item render');

		$(this.el).html(this.template(this.model.toJSON()))

		var that = this;

		_.delay(function(){
			$(that.el).addClass('visible');
			that.scroll = new iScroll('wrapper_schoolItem', {
				fadeScrollbar: true,
				hideScrollbar: true
			});
		}, 200)
		return this;
	},

	toggleShare: function(e){
		var $elem = $('#select_share_list')
		if($elem.hasClass('hide')){
			$elem.removeClass('hide')
		} else {
			$elem.addClass('hide')
		}
	},

	toggleLove: function(){

		var func = _.bind(function(){
			var url = this.model.get('isCollect') ? 'collect/item/del.ngi' : 'collect/item/add.ngi';
			Backbone.sync({
				url: App.config.host + url,
				data: {
					id: this.model.get('id')
				},
				success: _.bind(function(resp){
					this.model.toggle();

					var html = this.model.get('isCollect') ? '<div class="simple_msg"><img src="./img/right.png" alt="">收藏成功</div>' : '<div class="simple_msg">取消收藏</div>';

					App.dialog({
						dialogId: 'fav_result',
						duration: 3000,
						html:  html,
						mask: false
					});
				}, this)
			});
		}, this)

		App.Login.init(func)
	},

	toShare: function(e){

		var temp = _.bind(function(){
			if(App.view.schoolShare){
				$(App.view.schoolShare.el).remove();
				App.view.schoolShare = null;
			}

			App.view.schoolShare = new SchoolShareView({
				model: this.model,
				channel: 'qzone'
			});

			$('#select_share_list').addClass('hide');
		}, this);

		App.Login.init(temp, this)
	},

	toLeave: function(){
		$(this.el).removeClass('pt-page-moveFromRight').addClass('pt-page-moveToRight');
	}
});

var SchoolShareView = Backbone.View.extend({

	id: 'schoolShare',

	className: 'box pt-page-moveFromRight hidden',
	
	template: tpl['schoolShare'],

	events: {
		"tap .btn_y": "shareTo",
		'tap .btn_z': 'toLeave'
	},

	initialize: function (options) {

		console.log('school - Share');

		this.channel = options['channel'];

		_.bindAll(this, "render", "shareTo");

		App.el.append($(this.el));
		this.render();
	},

	render: function(){
		var map = {
			qzone: "QQ空间",
			weibo: "微博",
			weixin: "微信",
			renren: "人人网"
		}

		this.data = _.extend({
			channel: this.channel,
			channelName: map[this.channel],
			msg: "给大家分享一篇《"+ this.model.get('title') +"》的文章，超实用哦~~~ 每天十条美容贴士，发现美丽掌握美丽，每 天都为美丽加点分！"
		}, this.model.toJSON());

		$(this.el).html(this.template( this.data ));

		var that = this;
		_.delay(function(){
			$(that.el).addClass('visible');
		}, 200)

		return this;
	},

	shareTo: function(){
		console.log('share to');

		var that = this;
		App.share.qzone({
			title: this.data.title,
			url: "http://rc.qzone.qq.com/100670476",
			comment: this.data.msg,
			summary: this.data.summary,
			images: this.data.img
		}, function(res){
			if(res.ret == 0){
				var html = '<div class="simple_msg"><img src="./img/right.png" alt="">分享成功</div>';
				App.dialog({
					dialogId: 'qzone_share_ok',
					duration: 3000,
					html:  html,
					mask: false
				});

				that.toLeave();
			}
		});
	},

	toLeave: function(){
		$(this.el).removeClass('pt-page-moveFromRight').addClass('pt-page-moveToRight');
	}
});

// 我的学堂
var MySchool = Backbone.Collection.extend({

	model: School,

	url: App.config.host + 'collect/item/list.ngi',

	initialize: function(model, options) {

		this.perPage = 5;

		_.bindAll(this, 'parse', 'next', 'prev');

		this.on('sync', this.refresh, this);
	},

	refresh: function(){
		this.page = this.total ? this.askPage : 0;
	},

	fetchMe: function(args){

		args = args || {};

		this.askPage = args.page || 1;

		this.fetch({
			data: {page: this.askPage }
		});

	},

	parse: function(resp) {

		this.total = resp.total;
		this.pages = Math.ceil(this.total / this.perPage);

		return resp.data;

	},

	prev: function() {
		return (this.page > 1) ? this.fetchMe({page: this.page - 1}) : false;
	},

	next: function() {
		return (this.page < this.pages) ? this.fetchMe({page: this.page + 1}) : false;
	}
});

var MySchoolView = Backbone.View.extend({

	id: 'mySchool',

	className: 'box',

	template: tpl['mySchool'],

	events: {
		'tap .load_prev': "toPrev",
		'tap .load_next': "toNext",
		'tap article': 'toItem'
	},

	initialize: function (options) {

		App.collection.mySchool = new MySchool();
		this.collection = App.collection.mySchool

		_.bindAll(this, "toPrev", "toNext", "toItem");

		this.collection.on('sync', this.render, this);

		App.el.append($(this.el));

		$(this.el).html( this.template({
			items: [],
			page: 0,
			pages: 0
		}));

		this.show();
	},

	show: function(){

		console.log('myschool show');

		$('.box').addClass('hide');
		$(this.el).removeClass('hide');
		this.collection.fetchMe();
	},

	render: function () {
		console.log('myschool render');

		$(this.el).html(
			this.template({
				items: this.collection.toJSON(),
				pages: this.collection.pages,
				page: this.collection.page
			})
		)

		var that = this;
		_.delay(function(){
			App.scroll && (App.scroll.destroy(), App.scroll = null );
			App.scroll = new iScroll('wrapper_mySchool', {
				fadeScrollbar: true,
				hideScrollbar: true
			});
		}, 300)
		return this;
	},

	toItem: function(e){
		var model = this.collection.at($(e.currentTarget).index());

		console.log(model.toJSON());
		App.view.schoolItem = new SchoolItemView({
			model: model
		})
	},

	toPrev: function(e){
		$(e.currentTarget).html('正在加载...<span class="loading"></span>')
		this.collection.prev();
	},

	toNext: function(e){
		$(e.currentTarget).html('正在加载...<span class="loading"></span>')
		this.collection.next();
	}
});


// 论坛热帖、新帖、list
var Post = Backbone.Model.extend({

	defaults: function(){},

	initialize: function() {
	}
});

var Posts = Backbone.Collection.extend({

	model: Post,

	order: {},

	initialize: function(model, options) {

		this.fid = options.fid;
		this.perPage = 10;

		_.bindAll(this, 'parse', 'goPage', 'next', 'prev');

		this.on('sync', this.refresh, this)

	},

	refresh: function(){
		this.page = this.total ? this.askPage : 0;
		this.fid = this.askFid;
	},

	url: function(){

		var url = '';
		switch(this.fid){
			case 'hot':
				url = "bbs/threads/hot.ngi";
				break;
			case 'new':
				url = "bbs/threads/new.ngi";
				break;
			default:
				url = "bbs/threads/list.ngi";
		}

		return App.config.host + url
		
	},

	fetchMe: function(args){
		console.log(args);

		args = args || {};

		this.askFid = args.fid || this.fid;
		this.askPage = args.page || 1;

		console.log(this.askPage, this.askFid);

		this.fetch({
			success: args.success || function(){},
			data: _.extend({
				page: this.askPage,
				fid: this.askFid
			}, this.order)
		});

	},

	parse: function(resp) {

		if(resp.total){
			this.total = resp.total;
			this.pages = Math.ceil(this.total / this.perPage);
		}

		return resp.data;

	},

	goPage: function(page){

		if(page > 0 && page <= this.pages) {
			this.fetchMe({page: page});
		}
		return false;

	},

	prev: function() {
		return (this.page > 1) ? this.fetchMe({page: this.page - 1}) : false;
	},

	next: function() {
		return (this.page < this.pages) ? this.fetchMe({page: this.page + 1}) : false;
	}
	
});

var PostsView = Backbone.View.extend({

	id: '',

	className: 'box',

	events: {
		'tap .paging .first': "toFirst",
		'tap .paging .prev': "toPrev",
		'tap .paging .next': "toNext",
		'tap .paging .last': "toLast",
		'tap .toggle_select': 'toggleSort',
		'tap .drop_down_select li': 'bySort',
		'tap .btn_y': 'toPost'
	},

	initialize: function (options) {

		this.template = tpl[this.id];

		this.scrollId = options.scrollId;

		_.bindAll(this, "toFirst", "toPrev", "toNext", "toLast", "toggleSort", "bySort", 'toPost');

		this.collection.on('sync', this.render, this);

		$(this.el).html(
			this.template({
				items: [],
				pages: 0,
				page: 0,
				title: this.collection.title
			})
		)

		App.el.append($(this.el));

		this.show(); 
	},

	show: function(args){

		console.log('bbs' + this.collection.fid + 'list show');

		args = args || {};

		$('.box').addClass('hide');
		$(this.el).removeClass('hide');

		this.collection.fetchMe({
			fid: args.fid || this.collection.fid
		});
	},

	render: function () {
		console.log('bbs' + this.collection.fid + 'list render');

		$(this.el).html(
			this.template({
				items: this.collection.toJSON(),
				pages: this.collection.pages,
				page: this.collection.page,
				title: this.collection.title
			})
		)

		$(this.el).find('.drop_down_select').addClass('hide');

		var that = this;
		App.scroll && (App.scroll.destroy(), App.scroll = null );
		App.scroll = new iScroll(this.scrollId, {
			fadeScrollbar: true,
			hideScrollbar: true,
			onScrollStart: function(){
				$(that.el).find('.footer').removeClass('hide');
			}
		});
		return this;
	},

	bySort: function(e){
		var tmp = $(e.currentTarget).attr('data-order');

		switch(tmp){
			case 'newPosts':
				this.collection.order = {order: 1};
				this.collection.title = '最新发表';
				break;
			case 'lastReply':
				this.collection.order = {order: 0};
				this.collection.title = '最后回复';
				break;
			case 'digest':
				this.collection.order = {digest: 1};
				this.collection.title = '只看精华';
				break;
			case 'recommend':
				this.collection.order = {recommend: 1};
				this.collection.title = '只看推荐';
				break;
			default:
				// do nothing
		};

		console.log(this.collection.order);
		this.collection.fetchMe();
	},

	toggleSort: function(){
		var $sort = $(this.el).find('.drop_down_select');
		if($sort.hasClass('hide')){
			$sort.removeClass('hide');
		} else {
			$sort.addClass('hide')
		}
		
	},

	toFirst: function(){
		this.collection.goPage(1);
	},

	toPrev: function(){
		this.collection.prev();
	},

	toNext: function(){
		this.collection.next();
	},

	toLast: function(){
		this.collection.goPage(this.collection.pages)
	},

	toPost: function(){
		posting();
	}
});


// 论坛频道
var Forum = Backbone.Model.extend({

	defaults: function(){},

	initialize: function() {
	}
});

var Forums = Backbone.Collection.extend({

	model: Forum,

	url: App.config.host + 'bbs/forums/list.ngi',

	initialize: function() {
		this.fetch();
	},

	parse: function(resp) {
		return resp.data;
	}
});

var ForumsView = Backbone.View.extend({

	id: 'bbsSort',

	className: 'box',
	
	template: tpl["bbsSort"],

	events: {
		'tap .btn_y': 'toPost'
	},

	initialize: function () {

		_.bindAll(this, 'toPost')

		if(!App.collection.forums){
			this.collection = App.collection.forums = new Forums();
		} else {
			this.collection = App.collection.forums;
		}

		App.el.append($(this.el));

		this.collection.on('sync', this.render, this);
		this.show();
	},

	show: function(){
		$('.box').addClass('hide');
		$(this.el).removeClass('hide');
		this.render();
		return this;
	},

	render: function () {
		console.log('bbs sort list render');

		var items = this.collection.toJSON();
		$(this.el).html( this.template({items: items}) );

		if(items.length > 0){
			App.scroll && (App.scroll.destroy(), App.scroll = null );
			App.scroll = new iScroll('bbs_sort_list', {
				fadeScrollbar: true,
				hideScrollbar: true
			});
		}
	},

	toPost: function(){
		posting();
	}
});


// 论坛帖子 + 评论
var PostItem = Backbone.Model.extend({

	defaults: function(){},

	initialize: function() {
	}
});

var PostItems = Backbone.Collection.extend({

	model: PostItem,

	url: App.config.host + 'bbs/posts/list.ngi',

	defaults: function(){},

	initialize: function(attributes, options) {

		this.page = 1;
		this.tid = options.tid;
		this.perPage = 10;

		this.on('sync', this.refresh, this);
	},

	parse: function(resp, options) {
		console.log(this.page, this.askPage);

		this.total = (this.askPage == 1) ? (resp.total - 1) : resp.total;
		this.pages = Math.ceil(this.total / this.perPage);

		return resp.data;
	},

	refresh: function(){
		this.page = this.askPage || 1;
		this.tid = this.askTid;
	},

	fetchMe: function(args){
		console.log(args);

		args = args || {};

		this.askTid = args.tid || this.tid;
		this.askPage = args.page || 1;

		console.log(this.askPage, this.askTid);

		this.fetch({
			success: args.success || function(){},
			data: {
				page: this.askPage,
				tid: this.askTid
			}
		});
	},

	goPage: function(page){
		if(page > 0 && page <= this.pages) {
			this.fetchMe({page: page});
		}
		return false;
	},

	prev: function() {
		return (this.page > 1) ? this.fetchMe({page: this.page - 1}) : false;
	},

	next: function() {
		return (this.page < this.pages) ? this.fetchMe({page: this.page + 1}) : false;
	}
});

var PostItemView = Backbone.View.extend({

	id: 'bbsItem',
	className: 'box',
	
	template: tpl.bbsItem,

	events: {
		'tap .paging .first': "toFirst",
		'tap .paging .prev': "toPrev",
		'tap .paging .next': "toNext",
		'tap .paging .last': "toLast",
		'tap .fav': "addFav",
		'tap .js_reply': 'toReply'
	},

	initialize: function (options) {

		console.log(this.collection);

		_.bindAll(this, "toFirst", "toPrev", "toNext", "toLast", "addFav", "toReply");

		this.collection.on('sync', this.render, this);

		this.collection.fetchMe({
			tid: this.collection.tid,
			page: this.collection.page
		});

		App.el.append($(this.el));
	},

	show: function(args){
		$('.box').addClass('hide');
		$(this.el).removeClass('hide');

		this.collection.fetchMe(args);
	},

	render: function () {
		if(this.collection.page == 1){
			this.collection.post = this.collection.shift().toJSON();
		}

		console.log(this.collection);

		
		$(this.el).html( this.template({
			post: this.collection.post,
			comments: this.collection.toJSON(),
			tid: this.collection.tid,
			page: this.collection.page,
			pages: this.collection.pages,
			perPage: this.collection.perPage
		}));

		var that = this;
		App.scroll && (App.scroll.destroy(), App.scroll = null );
		App.scroll = new iScroll('postItem_area', {
			fadeScrollbar: true,
			hideScrollbar: true,
			onScrollStart: _.bind(function(){
				$(this.el).find('.footer').removeClass('hide');
			}, this)
		});

		return this;
	},

	addFav: function(){
		if(this.collection.post.isCollect){
			return;
		}

		var success = _.bind(function(resp){
			if(resp.ret == 0){
				alert('收藏成功');
				this.collection.fetchMe();
			}
		}, this);

		Backbone.sync({
			url: App.config.host + 'collect/thread/add.ngi',
			data: {
				tid: this.collection.tid
			},
			success: success
		});
	},

	toReply: function(e){

		var func = _.bind(function(){
			var elem = $(e.currentTarget),
				tid = elem.attr('data-tid'),
				pid = elem.attr('data-pid');

			console.log('bbsreply tid:' + tid + 'pid: ' + pid);

			App.view.bbsReply = new BbsReplyView({
				model: new Reply(),
				tid: tid,
				pid: pid
			});
		}, this);

		App.Login.init(func);
	},

	toFirst: function(){
		this.collection.goPage(1);
	},

	toPrev: function(){
		this.collection.prev();
	},

	toNext: function(){
		this.collection.next();
	},

	toLast: function(){
		this.collection.goPage(this.collection.pages)
	}
});


// 回复
var Reply = Backbone.Model.extend({

	url: App.config.host + 'bbs/posts/add.ngi',

	defaults: function(){},

	initialize: function() {
	},

	fetchMe: function(args){
		console.log('没有图片的回复', args)
		this.fetch({
			data: {
				tid: this.tid,
				pid: this.pid || '',
				message: args.message
			},
			success: args.success || function(){}
		});
	},
});

var BbsReplyView = Backbone.View.extend({

	id: 'bbsReply',
	className: 'box hidden pt-page-moveFromRight',
	
	template: tpl['bbsReply'],

	events: {
		'tap .select_photo': 'pic',
		'tap .btn_z': 'toLeave',
		'tap .btn_y': 'toPost',
		'tap textarea': 'toEdit'
	},

	initialize: function (args) {

		this.model.tid = args.tid;
		this.model.pid = args.pid || '';
		console.log(this.model);

		$('#' + this.el).remove();

		App.el.append($(this.el));

		_.bindAll(this, 'pic', "toLeave", "toEdit", "toPost");

		this.render();
	},

	render: function(){

		var data, placeholder;
		if(this.model.pid){
			data = _.find(App.collection.post.toJSON(), function(item, index){
				return item.pid = this.model.pid
			}, this);
			placeholder = '@' + data.author;
		} else {
			data = App.collection.post.post;
			placeholder = data.subject;
		}

		$(this.el).html(this.template({
			placeholder: placeholder
		}));

		this.img = $(this.el).find('.select_photo img');

		_.delay(_.bind(function(){
			$(this.el).addClass('visible');
			this.scroll = new iScroll('wrapper_bbs_post', {
				fadeScrollbar: true,
				hideScrollbar: true,
				onBeforeScrollStart: function (e) {
					var target = e.target;
					while (target.nodeType != 1) target = target.parentNode;
					if (target.tagName != 'SELECT' && target.tagName != 'INPUT' && target.tagName != 'TEXTAREA')
					e.preventDefault();
				}
			});
		}, this), 100)
	},

	pic: function(){
		console.log('select pic');

		App.Camera.init({}, _.bind(function(i, imageData){
			console.log('Camera select ok:', i, imageData);

			this.img.attr({
				src: imageData
			})
			this.model.imageData = imageData;
		}, this))
	},

	toLeave: function(){
		console.log('to leave');
		ztback = false;
		$(this.el).removeClass('pt-page-moveFromRight').addClass('pt-page-moveToRight');
	},

	toEdit: function(e){
		ztback = true;
	},

	toPost: function(){

		var that = this;

		var success = function(resp){
			console.log('publish ok:' + resp);

			alert('回复成功~');
			App.collection.post.fetchMe()
			that.toLeave();
		}

		var failed = function(resp){
			console.log('publish ok' + resp)
		}

		var message = $(this.el).find('textarea').val();

		console.log('message:', message);

		if(!message) {
			alert('字数不能为空');
			return;
		}

		if(this.model.imageData){
			App.Upload.img({
				uploadUrl: this.model.url,
				img: $(this.el).find('.select_photo img').attr('src'),
				data: {
					tid: this.model.tid,
					pid: this.model.pid,
					message: message
				}
			}, success, failed)
		} else {
			this.model.fetchMe({
				success: success,
				message: message
			});
		}
	}
});


// 发帖
var posting = function (){
	var func = function(){
		App.view.bbsReply = new BbsPublishView({
			model: new Publish()
		});
	}

	App.Login.init(func);
}

var Publish = Backbone.Model.extend({

	url: App.config.host + 'bbs/threads/add.ngi',

	initialize: function() {
	},

	fetchMe: function(args){
		console.log('没有图片的发帖', args)

		this.fetch({
			data: {
				subject: args.subject,
				message: args.message,
				fid: this.fid
			},
			success: args.success || function(){}
		});
	},
});

var BbsPublishView = Backbone.View.extend({

	id: 'bbsPublish',
	className: 'box hidden pt-page-moveFromRight',
	
	template: tpl['bbsPost'],

	events: {
		'tap .select_photo': 'pic',
		'tap .btn_z': 'toLeave',
		'tap .btn_y': 'toPost',
		'tap textarea': 'toEdit',
		'tap header .title': 'toggleSel',
		'tap .drop_down_select li': 'selectSort'
	},

	initialize: function (args) {

		$('#' + this.el).remove();

		App.el.append($(this.el));

		_.bindAll(this, 'pic', "toLeave", "toEdit", "toPost", 'toggleSel', "selectSort");

		this.render();
	},

	render: function(){

		$(this.el).html(this.template({}));

		this.img = $(this.el).find('.select_photo img');

		var temp = _.bind(function(){
			$(this.el).addClass('visible');
			this.scroll = new iScroll('wrapper_bbs_post', {
				fadeScrollbar: true,
				hideScrollbar: true,
				onBeforeScrollStart: function (e) {
					var target = e.target;
					while (target.nodeType != 1) target = target.parentNode;
					if (target.tagName != 'SELECT' && target.tagName != 'INPUT' && target.tagName != 'TEXTAREA')
					e.preventDefault();
				}
			});
		}, this);

		_.delay(temp, 100)
	},

	pic: function(){
		console.log('select pic');

		App.Camera.init({}, _.bind(function(i, imageData){
			console.log('Camera select ok:', i, imageData);

			this.img.attr({
				src: imageData
			})
			this.model.imageData = imageData;
		}, this))
	},

	toLeave: function(){
		console.log('to leave');
		ztback = false;
		$(this.el).removeClass('pt-page-moveFromRight').addClass('pt-page-moveToRight');
	},

	toEdit: function(e){
		ztback = true;
	},

	toPost: function(){

		var success = _.bind(function(resp){
				console.log('publish ok:' + resp);

				if(resp.ret == 0){
					alert('发表成功~');

					this.toLeave();
				} else if(resp.ret == 1){
					alert('失败了')
				}
			}, this),
			failed = function(resp){
				console.log('publish failed' + resp);
			}

		var subject = $(this.el).find('input').val()
		var message = $(this.el).find('textarea').val();

		console.log(subject, message);


		if(!subject){
			alert('主题不能为空');
			return;
		}

		if(!message) {
			alert('内容不能为空');
			return;
		}

		if(!this.model.fid){
			alert('分类不能为空');
			return;
		}

		if(this.model.imageData){
			App.Upload.img({
				uploadUrl: this.model.url,
				img: $(this.el).find('.select_photo img').attr('src'),
				data: {
					subject: subject,
					message: message,
					fid: this.model.fid
				}
			}, success, failed)
		} else {
			this.model.fetchMe({
				success: success,
				message: message,
				subject: subject
			});
		}
	},

	toggleSel: function(){
		var $sel = $('.drop_down_select');

		if($sel.hasClass('hide')){
			$sel.removeClass('hide')
		} else {
			$sel.addClass('hide')
		}
	},

	selectSort: function(e){

		var fid = $(e.currentTarget).attr('data-order');
		console.log(fid);
		this.model.fid = fid;

		$('header .title').html($(e.currentTarget).html());
		$('.drop_down_select').addClass('hide');
	}
});


// 助手
var Aide = Backbone.Model.extend({

	defaults: function(){},

	initialize: function() {
	}
});

var Aides = Backbone.Collection.extend({

	model: Aide,

	initialize: function() {}
});

var AidesView = Backbone.View.extend({

	id: 'aideList',
	className: 'box',
	
	template: tpl.aide,

	events: {
	},

	initialize: function () {
		App.el.append($(this.el));
		this.render().show();
	},

	show: function(){
		$('.box').addClass('hide');
		$(this.el).removeClass('hide');
	},

	render: function () {
		$(this.el).html( this.template({items: this.collection.toJSON()}) );

		App.scroll && (App.scroll.destroy(), App.scroll = null );
		App.scroll = new iScroll('aide_list', {
			fadeScrollbar: true,
			hideScrollbar: true
		});
		return this;
	}
});


var popup = function(args){
	var opts = _.extend({
		doneText: null,
		cancelText: null,
		callback: null,
		doneCallback: null,
		cancelCallback: null,
		msg: null
	}, args)


	var obj = App.dialog({
		dialogId: 'popup',
		html:  tpl['popup'](opts),
		success: opts.callback,
		closeback: opts.cancelCallback
	});

	obj.container.find('.ok').bind('tap', args.doneCallback);

	return obj;
}


// 个人中心
var UserData = Backbone.Model.extend({

	url: App.config.host + 'entry.ngi',

	defaults: {
		coin: 0,
		icon: "./img/avatar.png",
		id: "",
		level: 0,
		nickname: "我的账号"
	},

	initialize: function() {

	},

	parse: function(resp){
		if(resp.ret == 0){
			return resp.data.user;
		} else {
			console.log(resp);
			return this.defaults;
		}
	}
});

var MeView = Backbone.View.extend({

	id: 'me',
	className: 'box',
	
	template: tpl['me'],

	events: {
		'tap #my_account': 'account',
		'tap .btn_y': 'toProfile'
	},

	initialize: function () {

		_.bindAll(this, 'account', 'toProfile');

		this.model.on('sync', this.render, this);

		App.el.append($(this.el));
		this.show();
	},

	show: function(){
		$('.box').addClass('hide');
		$(this.el).removeClass('hide');
		this.render();

		if(App.Login.check()){
			this.model.fetch();
		}
		return this;
	},

	render: function () {
		$(this.el).html( this.template(this.model.toJSON()) );
	},

	account: function(){
		var func = _.bind(function(){
			this.model.fetch();
		}, this);

		App.Login.init(func, function(){
			this.model.fetch();
		}, this)
	},

	toProfile: function(){
		var func = _.bind(function(){
			App.view.profile = new ProfileView()
		}, this)

		App.Login.init(func, function(){
			this.model.fetch();
		}, this)
	}
});


// 设置
var Version = Backbone.Model.extend({

	url: App.config.host + 'version/latest.ngi',

	defaults: {
		version: '0.0.1',
		download: 'http://www.vanchu.com'
	},

	localStorage: new Store("version"),

	initialize: function() {
		this.on('change', this.store, this);
		
		var data = _.find(
			this.localStorage.findAll(), 
			function(value, index, list){
				return value.auth ? true : false;
			}, this);

		//data.version
	},

	store: function(method, model, options){
		this.id = this.get('version');
		this.localStorage.update(this);
	},

	parse: function(resp){
		return resp.data;
	}
});


var ProfileView = Backbone.View.extend({

	id: 'profileSet',

	className: 'box pt-page-moveFromRight hidden',

	template: tpl['myProfile'],

	events: {
		'tap .login_out': 'logout',
		'tap .check_version': 'version',
		'tap .about_colorful': 'about',
		'tap .js_goback': 'goback'
	},

	initialize: function () {
		$('#' + this.el).remove();

		if(App.model.version){
			this.model = App.model.version;
		} else {
			this.model = App.model.version = new Version();
		}
		
		_.bindAll(this, 'logout', 'version', "goback", "about");

		App.el.append(this.el);
		this.render();
	},

	render: function () {
		$(this.el).html( this.template({}) );

		_.delay(_.bind(function(){
			$(this.el).addClass('visible');
		}, this), 100)

		return this;
	},

	version: function(){
		this.model.fetch();
	},

	about: function(){
		App.view.aboutMe = new aboutView();
	},

	logout: function(){
		popup({
			doneText: '确定',
			cancelText: '取消',
			msg: '确认退出此账号？',
			doneCallback: _.bind(function(){
				App.Login.logout();
				this.goback();
			}, this)
		})
	},

	goback: function(){
		$(this.el).removeClass('pt-page-moveFromRight').addClass('pt-page-moveToRight');
	}
});


// 我的社区
var MyBbs = Backbone.Collection.extend({

	model: Post,

	initialize: function(model, options) {

		this.channel = options.channel;
		this.perPage = 10;
		_.bindAll(this, 'parse', 'next', 'prev');
		this.on('sync', this.refresh, this)
	},

	refresh: function(){
		this.page = this.total ? this.askPage : 0;
	},

	url: function(){

		var url = '';
		switch(this.channel){
			case 'receive':
				url = "bbs/my/reply/receive/list.ngi";
				break;
			case 'send':
				url = "bbs/my/reply/send/list.ngi";
				break;
			case 'collect':
				url = "collect/thread/list.ngi";
		}

		return App.config.host + url
		
	},

	fetchMe: function(args){
		console.log(args);

		args = args || {};

		this.askPage = args.page || 1;

		console.log(this.askPage);

		this.fetch({
			success: args.success || function(){},
			data: {
				page: this.askPage
			}
		});

	},

	parse: function(resp) {

		this.total = resp.total;
		this.pages = Math.ceil(this.total / this.perPage);

		return resp.data;

	},

	prev: function() {
		return (this.page > 1) ? this.fetchMe({page: this.page - 1}) : false;
	},

	next: function() {
		return (this.page < this.pages) ? this.fetchMe({page: this.page + 1}) : false;
	}
	
});

var MyBbsView = Backbone.View.extend({

	id: '',

	className: 'box',

	template: tpl['myBbs'],

	events: {
		'tap .load_prev': "toPrev",
		'tap .load_next': "toNext"
	},

	initialize: function (options) {

		this.scrollId = 'myBbs_list_' + this.collection.channel;

		_.bindAll(this, "toPrev", "toNext");

		this.collection.on('sync', this.render, this);

		App.el.append($(this.el));

		$(this.el).html( this.template({
			items: [],
			channel: this.collection.channel,
			page: 0,
			pages: 0
		}));

		this.show();
	},

	show: function(){

		console.log('myBbs' + this.collection.channel + 'list show');


		$('.box').addClass('hide');
		$(this.el).removeClass('hide');

		this.collection.fetchMe();
	},

	render: function () {
		console.log('myBbs' + this.collection.channel + 'list render');

		console.log(this.collection.channel);

		$(this.el).html(
			this.template({
				items: this.collection.toJSON(),
				channel: this.collection.channel,
				pages: this.collection.pages,
				page: this.collection.page
			})
		)

		var that = this;
		App.scroll && (App.scroll.destroy(), App.scroll = null );
		App.scroll = new iScroll(this.scrollId, {
			fadeScrollbar: true,
			hideScrollbar: true
		});
		return this;
	},

	toPrev: function(e){
		$(e.currentTarget).html('正在加载...<span class="loading"></span>')
		this.collection.prev();
	},

	toNext: function(e){
		$(e.currentTarget).html('正在加载...<span class="loading"></span>')
		this.collection.next();
	}

});

// about
var aboutView = Backbone.View.extend({

	id: 'aboutMe',

	className: 'box pt-page-moveFromRight hidden',

	template: tpl['aboutMe'],

	events: {
		'tap .js_goback': 'goback'
	},

	initialize: function (options) {

		$('#'+ this.id).remove();

		_.bindAll(this, "goback");

		App.el.append($(this.el));

		this.render();
	},

	render: function () {
		console.log('aboutMe - render');


		$(this.el).html(this.template({}));

		_.delay(_.bind(function(){
			$(this.el).addClass('visible');
		}, this), 100)
	},

	goback: function(){
		$(this.el).removeClass('pt-page-moveFromRight').addClass('pt-page-moveToRight');
	}
});


var Router = Backbone.Router.extend({

	routes: {
		'': 'school',
<<<<<<< HEAD

		// login
		'!/account': 'account',
=======
>>>>>>> dev

		// school
		'!/school': 'school',

		// bbs
		'!/bbs': 'bbsHot',
		'!/bbs/sort': 'bbsSort',

		'!/bbs/hot': 'bbsHot',
		'!/bbs/new': 'bbsNew',
		'!/bbs/:list': 'bbsList',
		'!/bbs/item/:tid': 'bbsItem',
		
		// aide
		'!/aide': 'aideList',

		// me
		'!/me': 'me',

		'!/me/mine': 'mine',

		'!/me/school': 'mySchool',

		'!/me/bbs': 'myBbs',
		'!/me/bbs/:channel': 'myBbs',

		'!/previous': 'previous'
	},

	initialize: function(){
		this.history = [];
		Backbone.history.on('all', this.storeRoute, this);
	},

	storeRoute: function() {
		this.history.push(Backbone.history.fragment);
	},

	previous: function (){
		if(this.history.length > 1){
			this.navigate( this.history[this.history.length - 2] , {trigger: true, replace: false});
			this.history.length = this.history.length - 3;
		} else {
			this.navigate( '' , {trigger: true});
		}
	},

	school: function(){
		if(!App.view.school){
			App.collection.school = new Schools();
			App.view.school = new SchoolView({
				collection: App.collection.school
			});
		} else {
			App.view.school.show();
		}
	},

	bbsHot: function(){
		if(!App.view.bbsHot){
			App.collection.bbsHot = new Posts('', {fid: 'hot'});
			App.view.bbsHot = new PostsView({
				collection: App.collection.bbsHot,
				fid: 'hot',
				id: 'bbsHot',
				scrollId: 'bbs_hot_list'
			});
		} else {
			App.view.bbsHot.show();
		}

	},

	bbsNew: function(){
		if(!App.view.bbsNew){
			App.collection.bbsNew = new Posts('', {fid: 'new'});
			App.view.bbsNew = new PostsView({
				collection: App.collection.bbsNew,
				fid: 'new',
				id: 'bbsNew',
				scrollId: 'bbs_new_list'
			});
		} else {
			App.view.bbsNew.show();
		}
	},

	bbsList: function(fid){
		if(!App.view.bbsList){
			App.collection.bbsList = new Posts('', {fid: fid});
			App.view.bbsList = new PostsView({
				collection: App.collection.bbsList,
				id: 'bbsList',
				scrollId: 'wrapper_bbs_list'
			});
		} else {
			App.view.bbsList.show({fid: fid});
		}
	},

	bbsSort: function(){
		if(!App.view.forums){
			App.view.forums = new ForumsView();
		} else {
			App.view.forums.show();
		}
	},

	bbsItem: function(tid){
		if(!App.view.post){
			App.collection.post = new PostItems('', {tid: tid});
			App.view.post = new PostItemView({
				collection: App.collection.post
			});
		} else {
			App.view.post.show({tid: tid});
		}
	},

	aideList: function(){
		if(!App.view.aideList){
			App.collection.aideList = new Aides();
			App.view.aideList = new AidesView({
				collection: App.collection.aideList,
			});
		} else {
			App.view.aideList.show();
		}
	},

	me: function(){
		if(!App.view.me){
			App.model.userData = new UserData();
			App.view.me = new MeView({
				model: App.model.userData
			});
		} else {
			App.view.me.show();
		}
	},

	mine: function(){

	},

	myBbs: function(channel){

	},

	mySchool: function(){

	}
});

$(_.bind(App.init, App));

})(window, undefined, window.App = window.App || {})